package com.choosefine.it.basedata.controller;

import com.choosefine.it.common.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import springfox.documentation.annotations.ApiIgnore;

import com.choosefine.it.base.BaseController;
import com.choosefine.it.base.dto.PageDTO;
import com.choosefine.it.basedata.model.UserInfo;
import com.choosefine.it.basedata.model.dto.FindUserCondition;
import com.choosefine.it.basedata.model.vo.UserInfoFindVO;
import com.choosefine.it.basedata.service.UserInfoService;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.utils.DateUtils;
import com.github.pagehelper.Page;

/**
 * 用户详情相关控制层
 * 
 * @author guwenwei 2016/11/16
 */
@RestController
@RequestMapping("/basedata/userinfo")
@Api(value = "用户详情相关", description = "顾文伟")
public class UserInfoController extends BaseController {
	
	@Autowired
	UserInfoService userinfoService;
	
	/**
	 * 刷新所有功能到Mongdb中同步
	 * 
	 * @param userinfo
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "刷新所有功能到Mongdb中同步" )
	@ResponseBody
	@GetMapping("/mongodb")
	public String userAll( ) {
		return responseSuccess(userinfoService.selectAll());
	}
	
	/**
	 * 添加用户
	 * 
	 * @param userinfo
	 * @param
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "存储用户详情", notes = "传入用户对象，存储相关用户详细信息")
	@ResponseBody
	@ApiResponses({
			@ApiResponse(code = ResultCode.SUCCESS_CREATED, message = "添加成功返回结果"),
			@ApiResponse(code = ResultCode.FAILED, message = "请求参数错误") })
	@RequestMapping(method = RequestMethod.POST)
	public String save(@RequestBody UserInfo userinfo) throws BusinessException{
		String result = null;
		if (userinfo != null) {
			userinfo.setCtime(DateUtils.getNowTime());
			Integer num = userinfoService.insert(userinfo);
			if (num > 0) {
				result = responseSuccess(num, ResultCode.SUCCESS_CREATED,
						ResultCode.MSG_CREATE_SUCCESS);
			} else {
				result = responseFail(ResultCode.MSG_ERROR);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	/**
	 * 修改用户
	 * 
	 * @param userinfo
	 * @param
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "修改用户详情")
	@ResponseBody
	@ApiResponses({
			@ApiResponse(code = ResultCode.SUCCESS_CREATED, message = "添加成功返回结果"),
			@ApiResponse(code = ResultCode.FAILED, message = "请求参数错误") })
	@RequestMapping(method = RequestMethod.PUT)
	public String update(@RequestBody UserInfo userinfo) {
		String result = null;
		if (userinfo != null) {
			userinfo.setUtime(DateUtils.getNowTime());
			Integer num = userinfoService.update(userinfo);
			if (num > 0) {
				result = responseSuccess(num, ResultCode.SUCCESS_CREATED,
						ResultCode.MSG_UPDATE_SUCCESS);
			} else {
				result = responseFail(ResultCode.MSG_ERROR);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	@ApiOperation(value = "根据用户编号取用户详情")
	@ApiImplicitParam(name = "userCode", value = "用户编号", required = true, dataType = "String", paramType = "path")
	@RequestMapping(value = "/userCode/{userCode}", method = RequestMethod.GET)
	public String getUserByUserCode(@PathVariable String userCode) {
		String result = null;
		if (!StringUtils.isEmpty(userCode)) {
			UserInfo userinfo = userinfoService.findByUserCode(userCode);
			result = responseSuccess(userinfo);
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	/**
	 * 12.2 dzq 服务器调用方法根据用户code调用
	 * 
	 * @param UserCode
	 * @return
	 */
	@ApiIgnore
	@ApiOperation(value = "根据用户编号取用户详情(服务器)")
	@ApiImplicitParam(name = "UserCode", value = "用户编号", required = true, dataType = "String")
	@RequestMapping(value = "/Server/{UserCode}", method = RequestMethod.GET)
	public String serverGetUserByUserCode(@PathVariable String UserCode) {
		String result = null;
		if (UserCode != null) {
			UserInfo userinfo = userinfoService.findByUserCode(UserCode);
			result = responseSuccess(userinfo);
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	@ApiOperation(value = "根据用户ID取用户详情")
	@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String getUserById(@PathVariable Integer id) {
		String result = null;
		if (id != null) {
			UserInfo userinfo = userinfoService.findByPrimaryKey(id);
			if (userinfo != null) {
				result = responseSuccess(userinfo);
			} else {
				result = responseFail(ResultCode.MSG_ERROR);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	@ApiOperation(value = "根据用户编号删除用户详情")
	@ApiImplicitParam(name = "userCodes", value = "用户编号", required = true, dataType = "String", paramType = "path")
	@RequestMapping(value = "/userCodes/{userCodes}", method = RequestMethod.DELETE)
	public String deleteByUserCode(@PathVariable String userCodes) {
		String result = null;
		if (userCodes != null) {
			Integer num = userinfoService.deleteByUserCode(userCodes);
			if (num > 0) {
				result = responseSuccess(num);
			} else {
				result = responseFail(ResultCode.MSG_ERROR);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	@ApiOperation(value = "根据用户手机号查询用户详情")
	@ApiImplicitParam(name = "phone", value = "用户手机号（注册时）", required = true, dataType = "String", paramType = "path")
	@RequestMapping(value = "/selectUserInfoByPhoneNum/{phone}", method = RequestMethod.GET)
	public String selectUserInfoByPhoneNum(@PathVariable String phone) {
		String result = null;
		if (phone != null && !"".equals(phone)) {
			UserInfo userinfo = userinfoService.selectUserInfoByPhoneNum(phone);
			if (userinfo != null) {
				result = responseSuccess(userinfo);
			} else {
				result = responseFail(ResultCode.MSG_ERROR);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;

	}

	/**
	 * @author chenjian
	 */
	@ApiOperation(value = "根据条件查询项目承包人或班组承包人或工人信息,roleId（1：工人 ；2：班组承包人；3：项目承包人）(陈健)", notes = "控制台-项目管理-新增项目",response=UserInfoFindVO.class)
	@RequestMapping(method = RequestMethod.POST, value = "/findUserListByRole", produces = "application/json")
	public String findUserListByRole(
			@RequestBody FindUserCondition findUserCondition) {
		Map<String, Object> params = new HashMap<>();
		String result = null;
		if (findUserCondition.getRoleId() != null) {
			// 角色id
			params.put("roleId", findUserCondition.getRoleId());
			// 租户编号或姓名
			if (findUserCondition.getCodeOrName() != null
					&& !"".equals(findUserCondition.getCodeOrName().trim())) {
				params.put("codeOrName", findUserCondition.getCodeOrName().trim());
			}
			PageDTO pageDto = new PageDTO();
			pageDto.setPageNum(findUserCondition.getPageNum());
			pageDto.setPageSize(findUserCondition.getPageSize());
			Page<UserInfoFindVO> userInfoList = userinfoService.findUserListByRole(
					pageDto, params);
			if (userInfoList.size()>0) {
				result = responseSuccess(userInfoList.toPageInfo(),
						ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
			} else {
				result = responseFail();
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_ERROR);
		}
		return result;
	}

	@RequestMapping(value = "/selectUserInfoByRealName/{realName}", method = RequestMethod.GET)
	public String findUsersByRealName(@PathVariable String realName){
		String result = null;
		if(realName!=null&&!"".equals(realName)){
			List<UserInfo> userinfo = userinfoService.findUsersByRealName(realName);
			if(userinfo.size()>0){
				result = responseSuccess(userinfo.get(0));
			}else{
				result = responseFail(ResultCode.MSG_ERROR);
			}
		}else{
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

/*	@ApiOperation(value = "查看工人证书(分页)")
	@RequestMapping(value = "/getskillsCcie",method = RequestMethod.GET,produces = "application/json")
	public String getskillsCcie(Integer pageSize,Integer pageNum){
		return null;
	}*/
	
	/**
	 * @Description：查询分包班组承包人信息,roleId 2：分包班组承包人(陈健)
	 * @Author：chenjian
	 * @Create Date：2017年2月23日
	 * @param：
	 * @return：
	 */
	@ApiOperation(value = "查询分包班组承包人信息,roleId 2：分包班组承包人(陈健)", notes = "控制台-项目管理-新增项目",response=UserInfoFindVO.class)
	@RequestMapping(method = RequestMethod.POST, value = "/findTeamUser", produces = "application/json")
	public String findTeamUser(@RequestBody FindUserCondition findUserCondition){
		Map<String, Object> params = new HashMap<>();
		String result = null;
		if (findUserCondition.getRoleId() != null) {
			// 角色id
			params.put("roleId", findUserCondition.getRoleId());
			// 租户编号或姓名
			if (com.choosefine.it.common.utils.StringUtils.isNotBlank(findUserCondition.getCodeOrName())) {
				params.put("codeOrName", findUserCondition.getCodeOrName().trim());
			}
//			if (com.choosefine.it.common.utils.StringUtils.isNotBlank(findUserCondition.getUserCode())) {
//				params.put("userCode", findUserCondition.getUserCode().trim());
//			}
			if (com.choosefine.it.common.utils.StringUtils.isNotBlank(findUserCondition.getProjectCode())) {
				params.put("projectCode", findUserCondition.getProjectCode().trim());
			}
			PageDTO pageDto = new PageDTO();
			pageDto.setPageNum(findUserCondition.getPageNum());
			pageDto.setPageSize(findUserCondition.getPageSize());
			Page<UserInfoFindVO> userInfoList = userinfoService.findTeamUser(pageDto, params);
			if (userInfoList.size()>0) {
				result = responseSuccess(userInfoList.toPageInfo(),
						ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
			} else {
				result = responseFail();
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_ERROR);
		}
		return result;
	}
	
	/**
	 * @Description：查询工人信息,roleId 1：工人(陈健)
	 * @Author：chenjian
	 * @Create Date：2017年2月23日
	 * @param：
	 * @return：
	 */
	@ApiOperation(value = "查询工人信息,roleId 1：工人(陈健)", notes = "控制台-项目管理-新增项目",response=UserInfoFindVO.class)
	@RequestMapping(method = RequestMethod.POST, value = "/findTeamWorkerUser", produces = "application/json")
	public String findTeamWorkerUser(@RequestBody FindUserCondition findUserCondition){
		Map<String, Object> params = new HashMap<>();
		String result = null;
		if (findUserCondition.getRoleId() != null) {
			// 角色id
			params.put("roleId", findUserCondition.getRoleId());
			// 租户编号或姓名
			if (com.choosefine.it.common.utils.StringUtils.isNotBlank(findUserCondition.getCodeOrName())) {
				params.put("codeOrName", findUserCondition.getCodeOrName().trim());
			}
//			if (com.choosefine.it.common.utils.StringUtils.isNotBlank(findUserCondition.getUserCode())) {
//				params.put("userCode", findUserCondition.getUserCode().trim());
//			}
			if (com.choosefine.it.common.utils.StringUtils.isNotBlank(findUserCondition.getProjectCode())) {
				params.put("projectCode", findUserCondition.getProjectCode().trim());
			}
			if (findUserCondition.getTeamId()!=null&&findUserCondition.getTeamId().intValue()>0) {
				params.put("teamId", findUserCondition.getTeamId());
			}
			PageDTO pageDto = new PageDTO();
			pageDto.setPageNum(findUserCondition.getPageNum());
			pageDto.setPageSize(findUserCondition.getPageSize());
			Page<UserInfoFindVO> userInfoList = userinfoService.findTeamWorkerUser(pageDto, params);
			if (userInfoList.size()>0) {
				result = responseSuccess(userInfoList.toPageInfo(),
						ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
			} else {
				result = responseFail();
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_ERROR);
		}
		return result;
	}
	
	/**
	 * @Description：检查身份证号是否重复，数据大于0表示已经存在（陈健）
	 * @Author：chenjian
	 * @Create Date：2017年3月10日
	 * @param：
	 * @return：
	 */
	@ApiOperation(value = "检查身份证号是否重复，数据大于0表示已经存在（陈健）", notes = "控制台-用户管理-个人类型租户管理")
	@RequestMapping(method = RequestMethod.GET, value = "/cardId", produces = "application/json")
	@ApiImplicitParams({
		@ApiImplicitParam(name="userType",value="用户角色（1：建筑工人2：分包承包人3：项目经理）",dataType="integer",paramType="query"),
		@ApiImplicitParam(name="cardId",value="身份证号码",required=true,dataType="String",paramType="query")
	})
	public String checkCardId(Integer userType,String cardId){
		String result = null;
		if (com.choosefine.it.common.utils.StringUtils.isNotBlank(cardId)) {
			Map<String, Object> params = new HashMap<>();
			params.put("userType", userType);
			params.put("cardId", cardId);
			Integer num = userinfoService.checkCardId(params);
			result = responseSuccess(num);
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_ERROR);
		}
		return result;
	}
}
